package com.demo.component.ollama.generate.impl;

import com.demo.component.ollama.generate.inter.OllamaService;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.client.transport.StdioClientTransport;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import reactor.core.publisher.Flux;

import java.io.*;
import java.nio.charset.StandardCharsets;


@Service("OllamaServiceImpl")
public class OllamaServiceImpl implements OllamaService {

    private final ChatClient chatClient;

    private String systemPrompt = "";

    @Autowired
    public OllamaServiceImpl(ChatClient.Builder chatClientBuilder,//McpSyncClient mcpClient,
                             ToolCallbackProvider tools) {

        //this.chatClient = chatClientBuilder.defaultToolCallbacks(new SyncMcpToolCallbackProvider(mcpClient), tools).build();

        //this.chatClient = chatClientBuilder.defaultToolCallbacks(new SyncMcpToolCallbackProvider(mcpClient)).build();

        this.chatClient = chatClientBuilder.defaultToolCallbacks(tools).build();

        try {
            File file = ResourceUtils.getFile("classpath:system-prompt.txt");

            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String line;
            while ((line = reader.readLine()) != null) {
                systemPrompt += line;
            }
        }
        catch (IOException e) {

        }

        //this.chatClient = chatClientBuilder.defaultToolCallbacks(tools).build();   SSE直接加到这里
    }


    @Override
    public String generateAnswer(String prompt) {

        return this.chatClient.prompt()
                .system(this.systemPrompt)
                .user(prompt)
                .call()
                .content();
    }

    @Override
    public Flux<ChatResponse> generateStream(String prompt) {

        return this.chatClient.prompt().system(this.systemPrompt).user(prompt).stream().chatResponse();
    }
}
